/*
 * @Author: yanjinzhong
 * @Date: 2021-04-12 19:01:15
 * @Description: file content
 */
import { defineConfig } from 'vite';
import path from 'path';
import viteSvgIcons from 'vite-plugin-svg-icons';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { buildConfig } from './build/config/buildConfig';
import styleImport from 'vite-plugin-style-import';

/**
 * @description: 添加生成svg雪碧图
 * @author: yanjinzhong
 */
const svgSprite = () => {
  return viteSvgIcons({
    iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
    symbolId: 'icon-[dir]-[name]',
  });
};

/**
 * 使用dotenv模块,将.env文件加载到process.env中
 */
const fs = require('fs');
const dotenv = require('dotenv');
const envFiles = [/** default file */ `.env.development`];
for (const file of envFiles) {
  const envConfig = dotenv.parse(fs.readFileSync(file));
  for (const k in envConfig) {
    process.env[k] = envConfig[k];
  }
}

/** 按需加载and-design-vue组件 */
const antdesign = styleImport({
  libs: [
    {
      libraryName: 'ant-design-vue',
      esModule: true,
      resolveStyle: (name: string) => {
        return `ant-design-vue/es/${name}/style/css`;
      },
    },
  ],
});

export default defineConfig({
  server: {
    port: 8888,
    proxy: {
      '/api': {
        target: process.env.VITE_API,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      '/mock': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/mock/, ''),
      },
    },
    hmr: {
      overlay: true,
    },
    open: false,
  },
  build: buildConfig,
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      comps: path.resolve(__dirname, './src/components'),
      config: path.resolve(__dirname, './src/config'),
      router: path.resolve(__dirname, './src/router'),
      store: path.resolve(__dirname, './src/store'),
      styles: path.resolve(__dirname, './src/styles'),
      type: path.resolve(__dirname, './src/type'),
      views: path.resolve(__dirname, './src/views'),
      utils: path.resolve(__dirname, './src/utils'),
      hooks: path.resolve(__dirname, './src/hooks'),
    },
  },
  css: {
    postcss: {
      plugins: [require('tailwindcss'), require('autoprefixer')],
    },
  },
  optimizeDeps: {
    include: [],
  },
  plugins: [vue(), vueJsx(), antdesign, svgSprite()],
});
